// 获取api base url
export const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;

console.log('apiBaseUrl', apiBaseUrl);

// 封装 get,post,put,delete 请求
export const post = async (path, data) => {
  const response = await fetch(`${apiBaseUrl}${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });
  if (!response.ok) {
    const error = await response.json();
    throw new Error(`${error.error}`);
  }
  return response.json();
};

export const get = async (path, params={}) => {
  try {
    // params remove undefined
    const removeUndefinedParams = Object.fromEntries(Object.entries(params).filter(([_, value]) => value !== undefined && value !== null));
    const queryString = new URLSearchParams(removeUndefinedParams).toString()
    console.log(`GET ${apiBaseUrl}${path}?${queryString}`);
    const response = await fetch(`${apiBaseUrl}${path}?${queryString}`, {
      method: 'GET',
      cache: 'no-store',
    });
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`${error.error}`);
    }
    return response.json();
  } catch (error) {
    throw error;
  }
};

export const put = async (path, data) => {
  try {
    console.log(`PUT ${apiBaseUrl}${path}`);
    const response = await fetch(`${apiBaseUrl}${path}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`${error.error}`);
    }
    return response.json();
  } catch (error) {
    throw error;
  }
};

export const del = async (path, data={}) => {
  try {
    console.log(`DELETE ${apiBaseUrl}${path}`);
    const response = await fetch(`${apiBaseUrl}${path}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`${error.error}`);
    }
    return response.text();
  } catch (error) {
    throw error;
  }
};

export const patch = async (path, data) => {
  try {
    console.log(`PATCH ${apiBaseUrl}${path}`);
    const response = await fetch(`${apiBaseUrl}${path}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    });
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`${error.error}`);
    }
    return response.json();
  } catch (error) {
    throw error;
  }
};


